//
// Created by daiyizheng on 2022/3/27.
//
#include <iostream>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution{
private:
    TreeNode *x, *y,*pre;
public:
    void recoverTree(TreeNode* root) {
        dfs(root);

        int tmp = x->val;
        x->val = y->val;
        y->val = tmp;

    }

    void dfs(TreeNode * node){
        if(!node)return;
        dfs(node->left);

        if(pre && node->val < pre->val){
            y = node;
            if (x== nullptr){
                x = pre;
            }else{
                return;
            }
        }
        pre = node;
        dfs(node->right);

    }
};